package com.example.result

import android.os.Environment
import androidx.test.uiautomator.By
import androidx.test.uiautomator.BySelector
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiObject2
import androidx.test.uiautomator.Until
import java.io.File

const val LAUNCH_TIMEOUT = 5000L

fun UiDevice.waitAndFindObject(
    condition: BySelector, needScroll: Boolean = false
): UiObject2? {
    wait(Until.hasObject(condition), LAUNCH_TIMEOUT)
    if (needScroll) {
        repeat(4) {
            findObject(By.scrollable(true))
                .scrollUntil(Direction.DOWN, Until.hasObject(condition))
        }
    }
    val findObject = findObject(condition)
    return findObject
}

fun UiDevice.launchActivity(
    packageName: String,
    activityName: String?
) {
    executeShellCommand("am start -n ${packageName}/$activityName")
    wait(
        Until.hasObject(By.pkg(packageName).depth(0)),
        LAUNCH_TIMEOUT
    )
}

fun UiDevice.takeScreenshot() {
    takeScreenshot(File("${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath}/${System.currentTimeMillis()}.png"))
}

